#!/bin/bash



# 需要按照tag的数字来排序
imagesCount=`docker images | grep 'hello-world-image' | sort -k 2 -n |wc -l`

echo "现在共有 $imagesCount 个 hello-world-image 镜像"
deleteCount=`expr $imagesCount - 2`
if [ $deleteCount -gt 0 ]
then
    echo "删除旧的镜像"

    docker images | grep 'hello-world-image' | sort -k 2 -n | awk '{print $3}' $img |head -n $deleteCount| xargs docker rmi


fi

existContainerCount=`docker ps -a | grep 'hello-world-image' | wc -l`


if [ $existContainerCount -gt 0 ]
then
   echo "删除现有的 $existContainerCount 个容器"

   docker ps -a | grep 'hello-world-image' | awk '{print $1}'| xargs docker stop $containerId| xargs docker rm $containerId

else
   echo "第一次运行，不需要移除旧的容器"
fi

